package com.ruoyi.framework.websocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.EndpointConfig;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * author:walker
 * time: 2023/6/28
 * description:  平台同步
 */
@Component
@Slf4j
// 类似于controlelr 服务点
@ServerEndpoint (value = "/ws/platofrmAsync/{userId}")
public class PlatformAsyncWebSocket {

    // 用来存储每一个客户端对象对应的WsController对象
    private static Map <String, PlatformAsyncWebSocket> onlineUsers = new ConcurrentHashMap <>();

    // 声明Session对象，通过该对象可以给指定的用户发送请求
    private Session session;

    /**
     * 连接建立时被调用
     */
    @OnOpen
    public void onOpen (Session session, EndpointConfig config) {
        log.info("连接成功");
        // 将局部的session对象赋值给成员session对象
        this.session = session;
        // 这里是因为前端在传数据的时候，会将userId传过来
        //所以使用将userId和websocket对象存储起来，方便下次服务端推送信息的时候使用
        Map <String, List <String>> requestParameterMap = this.session.getRequestParameterMap();
        List <String> userIds = requestParameterMap.get("userId");
        String userId = userIds.get(0);
        onlineUsers.put(userId, this);

    }

    /**
     * 接收到客户端消息时被调用
     */
    @OnMessage
    public void onMessage (String message, Session session) {

    }

    /**
     * 连接被关闭时调用
     */
    @OnClose
    public void onClose (Session session) {
        //关闭时则将map中的用户移除
        Map <String, List <String>> requestParameterMap = session.getRequestParameterMap();
        List <String> userIds = requestParameterMap.get("userId");
        String userId = userIds.get(0);
        onlineUsers.remove(userId);
    }

    //推送消息
    //将消息推送给某个指定的用户
    public void sendMsg (String userId, String message) {
        try {
            PlatformAsyncWebSocket wsController = onlineUsers.get(userId);
            wsController.session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            log.error("用户{} 发送信息{}失败,异常信息：{}", userId, message, e.getMessage());
        }

    }


}
